//
//  ST_MyPhotoViewController.swift
//  btvideo
//
//  Created by mac on 2020/1/6.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import KDDragAndDropCollectionViews
import HandyJSON
import TZImagePickerController
import SwiftyUserDefaults
import SwiftyJSON

//编辑个人照片 - Controller
class ST_MyPhotoViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title_nav_btn.setTitleForAllStates("编辑个人照片")
        
         
        
        view.backgroundColor = Color.clear
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(own_navigation_bar.snp.bottom)
        }
        
//        view.addSubview(add_btn)
//        add_btn.snp.makeConstraints { (make) in
//            make.width.equalTo(260)
//            make.height.equalTo(40)
//            make.centerX.equalToSuperview()
//            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-25)
//        }
        
        self.drag_and_drop_manager = KDDragAndDropManager.init(canvas: self.view, collectionViews: [collectionView])
        
        fetch_user_photos()
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(changeAvatarOberser(notification:)), name: NSNotification.Name.my_avatar_updated, object: nil)
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        var originalArray = data_array
        
        if originalArray.count < 1{
            return
        }
        
        originalArray[0] = avatar_model
        
        let url_array = originalArray.filtered({ (m) -> Bool in
            return m.uploadStatus == .success
        }) { (model) -> String in
            return model.content
        }
        
        
        print("bug2266-排序完成的URL：",url_array)
        
        self.sort_closure?(url_array)
        
        ST_MyPhotosSortManager.shared.dis_appear_hanlde(data_array: originalArray)
        
    }
    
    
//    MARK: - Reuqest Response
    fileprivate func fetch_user_photos(){
        
        JVrequest(PH.myPhotosApi, success: { (json) in
            
            print("bug2266:",json)
            
            guard var array = [ST_MyPhotoCollectionCellModel].deserialize(from: json["data"].rawString() ?? "") as? [ST_MyPhotoCollectionCellModel] else{
                return
            }
            
            if array.count < 1{
                
                self.data_array.removeAll()
                
                self.collectionView.reloadData()
                
                return
            }
            
//            返回数据第一个为 头像
            self.avatar_model = array.removeFirst()
            
//            始终保留第一个位置是【+】 cell ，添加一个空的 Model
            array.insert(ST_MyPhotoCollectionCellModel(), at: 0)
            
            self.data_array = array
            
            self.collectionView.reloadData()
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
    }

    //    MARK: - block
    var append_closure:((ST_PairsShareParticularModel)->())?
    
    var sort_closure:(([String])->())?
    //    MARK: - Data Array
        
    fileprivate var data_array = [ST_MyPhotoCollectionCellModel]()
    
    fileprivate var avatar_model = ST_MyPhotoCollectionCellModel()
    
    fileprivate var avatar_header_view : ST_MyPhotoCollectionReusableView?

    fileprivate var addCell:MyPhotoAddButtonCell?
    
    fileprivate weak var uploading_video_model:ST_MyPhotoCollectionCellModel?
    
//    MARK: - properties
    fileprivate lazy var add_btn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 40/2.0
        control.setTitleForAllStates("添加照片")
        control.setTitleColorForAllStates(UIColor.white)
        control.addTarget(self, action: #selector(add_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
       let controlLayout = UICollectionViewFlowLayout()
        controlLayout.headerReferenceSize = headerSize
        controlLayout.minimumInteritemSpacing = 5
        controlLayout.minimumLineSpacing = 5
        controlLayout.sectionInset = UIEdgeInsets.init(top: 10, left: 15, bottom: BTSafeAreaBottom + 100, right: 15)
        controlLayout.itemSize = cellSize
        return controlLayout
    }()
    
    fileprivate lazy var headerSize = CGSize.init(width: ScreenWidth , height: (ScreenWidth - 30)/345.0*355.0+48)
    
    fileprivate lazy var itemWidth:CGFloat = {
        return  ((ScreenWidth - 30 - 10)/3.0).int.cgFloat
    }()
    
    fileprivate lazy var cellSize = CGSize.init(width:itemWidth, height:itemWidth)
    
//
    
    fileprivate lazy var collectionView:KDDragAndDropCollectionView = {
        let control = KDDragAndDropCollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_MyPhotoCollectionCell.self)
        control.register(cellWithClass: MyPhotoAddButtonCell.self)
        
        control.register(supplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withClass: ST_MyPhotoCollectionReusableView.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.backgroundColor = Color.white
        
        control.alwaysBounceVertical = true
        
        return control
    }()
    
    fileprivate var drag_and_drop_manager : KDDragAndDropManager?

    fileprivate lazy var match_loading:ST_MatchFaceLoadingController = {
        
        let loading = ST_MatchFaceLoadingController()
    
        loading.overCurrentContext = true
    
        return loading
    }()
}


extension ST_MyPhotoViewController:KDDragAndDropCollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    
//    MARK:- 拖拽移动
    
    func collectionView(_ collectionView: UICollectionView, cellIsDraggableAtIndexPath indexPath: IndexPath) -> Bool {
        
        if indexPath.row == 0{
            return false
        }
        
        let item = data_array[indexPath.row]
        
        return item.uploadStatus == .success && item.state == 3
    }
    func collectionView(_ collectionView: UICollectionView, cellIsDroppableAtIndexPath indexPath: IndexPath) -> Bool {
        
        if indexPath.row == 0{
            return false
        }
        
        let item = data_array[indexPath.row]
        
        return item.uploadStatus == .success && item.state == 3
    }
    
    func collectionView(_ collectionView: UICollectionView, deleteDataItemAtIndexPath indexPath: IndexPath) {
        
        data_array.remove(at: indexPath.item)
        
    }
    
    
    func collectionView(_ collectionView: UICollectionView, insertDataItem dataItem: AnyObject, atIndexPath indexPath: IndexPath) {
        
        data_array.insert(dataItem as! ST_MyPhotoCollectionCellModel, at: indexPath.item)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, moveDataItemFromIndexPath from: IndexPath, toIndexPath to: IndexPath) {
        
        let fromDataItem = data_array[from.item]
        
        data_array.remove(at: from.item)
        
        data_array.insert(fromDataItem, at: to.item)
        
    }
    
    func collectionView(_ collectionView: UICollectionView, dataItemForIndexPath indexPath: IndexPath) -> AnyObject {
        return data_array[indexPath.item] as AnyObject
    }
    
    
    func collectionView(_ collectionView: UICollectionView, indexPathForDataItem dataItem: AnyObject) -> IndexPath? {
        
        if let item =  dataItem as? ST_MyPhotoCollectionCellModel{
            
            let f = data_array.firstIndex { (i) -> Bool in
                return i == item
            }
            
            if let idx = f{
                
                let r = Int(idx)
                
                return IndexPath.init(row: r, section: 0)
            }
        }
        
        return nil
    }
    
//    MARK:- 数据源&&delegate
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return cellSize
        
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let reuseView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withClass: ST_MyPhotoCollectionReusableView.self, for: indexPath)
        
        reuseView.model = avatar_model
        
        reuseView.uploadClosure = {
//            self?.upload_avatar_handle()
            ST_ChangeAvatarManager.shared.hud_root_controller = self
            ST_ChangeAvatarManager.shared.upload_avatar_handle()
        }
        
        self.avatar_header_view = reuseView
        
        return reuseView
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        if indexPath.row == 0{
        
            let cell = collectionView.dequeueReusableCell(withClass: MyPhotoAddButtonCell.self, for: indexPath)
            
            cell.current_photo_count = data_array.count
            
            self.addCell = cell
            
            return cell
        }
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_MyPhotoCollectionCell.self, for: indexPath)
        
        if let m = data_array[safe:indexPath.item]{
            cell.model = m
        }
        
        cell.isHidden = false
        
        if let kdCollectionView = collectionView as? KDDragAndDropCollectionView {
            
            if let draggingPathOfCellBeingDragged = kdCollectionView.draggingPathOfCellBeingDragged {
                
                if draggingPathOfCellBeingDragged.item == indexPath.item {
                    
                    cell.isHidden = true
                    
                }
            }
        }
        
        cell.deleteClosure = {[weak self] icell in
            self?.delete_handle(cell: icell)
        }
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        
        
        if indexPath.row == 0 {
            
            add_handle()
            
        }else{
            
            print("点击cell 测试")
        }
        
    }
    
    
    
}

//MARK:- Event
extension ST_MyPhotoViewController:TZImagePickerControllerDelegate{
    
    func delete_handle(cell:ST_MyPhotoCollectionCell){
        
        guard let indexPath = collectionView.indexPath(for: cell) else { return  }
        
        let param = ["id":cell.model.id]
        
        JVrequest(PH.deleteMyPhotoApi,parameters:param, success: { (json) in
            
            self.collectionView.performBatchUpdates({
                
                self.data_array.remove(at: indexPath.row)
                self.collectionView.deleteItems(at: [indexPath])
                
            }, completion: {(f) in
//                这样写 有bug
//                self.addCell?.current_photo_count = self.data_array.count
            })
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
    }
    
    @objc func upload_avatar_handle(){
        
        
        guard let vc = TZImagePickerController.init(maxImagesCount: 1, delegate: self) else{ return }
        vc.allowPickingVideo = false
        vc.didFinishPickingPhotosHandle = {[weak self] photos,assets,isSelectOriginalPhoto in
            
            if let image = photos?.first,let dt = image.pngData(){
                
               let content_key = UUID().uuidString
               
                self?.avatar_model.localImage = image
                
                self?.collectionView.reloadData()
                
                self?.show_indeterminate_h_u_d()
                
               JVUpload(fileKey: content_key, data: dt, uploadProgress: { (f) in
                   
               }, success: { (json) in
                   
                let p = ["avatar":content_key,"width":image.size.width,"height":image.size.height] as [String : Any]
                   
                   self?.push_to_remote(param: p)
                   
               }) { (code, err) in
                   
                   print("上传图片失败 ")
                   
                   ToastHud(text: err, view: self?.view)
               }
            }
        }
                    
        GlobalPresent(toController: vc, animated: true)
        
    }
    
    
    fileprivate func push_to_remote(param:[String:Any]){
        
        var displayLoading = false
        if [2,3].contains(FACE_AVATAE_STATE) {
            displayLoading = true
            GlobalPresent(toController: match_loading)
        }
        
        JVrequest(PH.changeAvatarApi,parameters:param, success: { (json) in
            
            print("换头像成功:",json)
            
            FACE_AVATAE_STATE = json["data"]["face_avatar_state"].intValue
            
            
            if let avatar = param["avatar"] as? String{
                self.avatar_model.content_key = avatar
            }
            
            self.hidden_indeterminate_h_u_d()
            
            NotificationCenter.default.post(name: Notification.Name.my_pairs_user_info_updated, object: nil)
            
            if displayLoading{
                
                self.match_loading.dismiss(animated: true) {
                    if FACE_AVATAE_STATE == 3{
                        GlobalPresent(toController: ST_MatchFaceSuccessController())
                    }
                    
                }
                
            }else{
            
                if FACE_AVATAE_STATE == 3{
                    GlobalPresent(toController: ST_MatchFaceSuccessController())
                }
            }
            
        }) { (code, err) in
            
            print("换头像失败:",err)
            
            if displayLoading{
                self.match_loading.dismiss(animated: true) {
                    self.displayError(code: code, err: err)
                }
            }else{
                self.displayError(code: code, err: err)
            }
            
        }
        
    }
    
    fileprivate func displayError(code:Int,err:String){
        
        if code == 400{
            let errorView = ST_ProfileErrorView()
            self.view.addSubview(errorView)
            errorView.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            errorView.errorStr = err
            self.hidden_indeterminate_h_u_d()
        }else{
            ToastHud(text: err, view: self.view)
        }
        
    }
    
    
    @objc fileprivate func changeAvatarOberser(notification:Notification){
        
        let json = JSON.init(notification.userInfo ?? "")
        
        self.avatar_model.localImage = notification.userInfo?["localImage"] as? UIImage
        self.avatar_model.content_key = json["avatarKey"].stringValue
        
        self.avatar_header_view?.model = self.avatar_model
        
        NotificationCenter.default.post(name: Notification.Name.my_pairs_user_info_updated, object: nil)
        
    }
    
    @objc func add_handle(){
        
        
        if self.data_array.count == 10{
            
            ToastHud(text: "最多只能上传10张哦", view: self.view)
            
            return
        }
        
        if let vc = TZImagePickerController.init(maxImagesCount: 1, delegate: self){
//            vc.allowPickingVideo = false
            vc.didFinishPickingPhotosHandle = {[weak self] photos,assets,isSelectOriginalPhoto in
                
                if let image = photos?.first{
                    
                    let m = ST_MyPhotoCollectionCellModel.init(image: image)
                    
                    self?.data_array.append(m)
                    
                    self?.collectionView.reloadData()
                    
                    self?.upload(model: m)
                    
                }
            }
            
            vc.didFinishPickingVideoHandle = {[weak self] image , assets in
                
                guard let ast = assets , let thumbnail = image else { return  }
                
                let options: PHVideoRequestOptions = PHVideoRequestOptions()
                           options.version = .original
                
               PHImageManager.default().requestAVAsset(forVideo: ast, options: options, resultHandler: { (asset, audioMix, info) in
                
                   if let urlAsset = asset as? AVURLAsset{
                    
                    let localVideoUrl = urlAsset.url
                    
                    let m = ST_MyPhotoCollectionCellModel.init(image: thumbnail, videoPath: localVideoUrl.path,videoSeconds:urlAsset.duration.seconds)
                    
                    main_thread_execute {
                     
                        self?.data_array.append(m)
                        
                        self?.collectionView.reloadData()
                        
                        self?.upload(model: m)
                        
                    }
                   }
               })
                
                
                print("当前选中视频")
            }
            
            
            
            
            GlobalPresent(toController: vc, animated: true)
        }
        
        
    }
    
}




//MARK:- Upload operation

/*
extension ST_MyPhotoViewController{
    
    
    func onPublishProgress(_ uploadBytes: Int, totalBytes: Int) {
        
        guard let currModel = uploading_video_model else { return }
        
        let percent = (uploadBytes.cgFloat/totalBytes.cgFloat*100).int
        
        main_thread_execute {
            
             print("上传视频打印f:",percent)
            
            currModel.uploadImageProgress = percent
            
            self.modifyCellIndicator(key: currModel.content_key)
        }
        
    }
    
    func onPublishComplete(_ result: TXPublishResult!) {
    
        
        guard let currModel = uploading_video_model else { return }
        
        if result.retCode != 0{
            
            ToastHud(text: "上传失败，请重新再试", view: self.view)
            
            currModel.uploadStatus = .failure
            
            self.modifyCellIndicator(key: currModel.content_key)
            
            
            print("上传失败：",result.descMsg ?? "❌")
            
            return
        }
        
        let videoURL = result.videoURL ?? ""
        let coverURL = result.coverURL ?? ""
        
        currModel.video_url = videoURL
        
        currModel.content = coverURL
        
        currModel.content_key = coverURL
        
        self.push_to_remote(model: currModel)
        
    }
 */
    
    
extension ST_MyPhotoViewController{
    
    fileprivate func upload(model:ST_MyPhotoCollectionCellModel){
        
        if model.type == 2{
            
            self.upload(imageModel: model)
            
        }else if model.type == 1{
         
            self.upload(videoModel: model)
        }
    }
    
    fileprivate func upload(videoModel:ST_MyPhotoCollectionCellModel){
        
        guard let path = videoModel.localVideoUrl , let img = videoModel.localImage ,let imgData = img.pngData()else { return }
        
        
        
        JVUpload(videoPath: path, coverImage: imgData, uploadProgress:  { (f) in
            
            main_thread_execute {
                
                videoModel.uploadImageProgress = (f*100).int
                
                self.modifyCellIndicator(key: videoModel.content_key)
            }
            
        },success: { (key0, key1) in
            
            let videoURL = key1
            let coverURL = key0
            
            videoModel.video_url = videoURL
            
            videoModel.content = coverURL
            
            videoModel.content_key = coverURL
            
            self.push_to_remote(model: videoModel)
            
            
        },failure: { (code, err) in
            
            print("uploadVideoFileToCloud Error:-",err)
            
            ToastHud(text: "上传失败，请重新再试", view: self.view)
            
            videoModel.uploadStatus = .failure
            
            self.modifyCellIndicator(key: videoModel.content_key)
            
            
        })
        
        
    }
    
    
    fileprivate func upload(imageModel:ST_MyPhotoCollectionCellModel){
        
        guard let img = imageModel.localImage,let dt = img.pngData() else { return }
        
        JVUpload(fileKey: imageModel.content_key, data: dt, uploadProgress: {[weak self] (f) in
            
            main_thread_execute {
                
                 print("上传图片打印f:",f)
                
                imageModel.uploadImageProgress = Int(f * 100)
                
                self?.modifyCellIndicator(key: imageModel.content_key)
            }
            
        }, success: { (json) in
            
            imageModel.content = Defaults[.QNResourcePrefix] + "/" + imageModel.content_key
            
            self.push_to_remote(model: imageModel)
            
        }) { (code, err) in
            
            print("上传图片失败 content_key：",imageModel.content_key)
            
            imageModel.uploadStatus = .failure
            
            self.modifyCellIndicator(key: imageModel.content_key)
        }
        
        
    }
    
    
    fileprivate func push_to_remote(model:ST_MyPhotoCollectionCellModel){
        
        var param = ["content":model.content_key,"width":model.width,"height":model.height] as [String : Any]
        
        
        let append_model = ST_PairsShareParticularModel()
        append_model.type = ST_PairsMotifType.image
        append_model.width = model.width
        append_model.height = model.height
        append_model.imageUrl = model.content
        
        if !model.video_url.isEmpty{
            param.updateValue(model.video_url, forKey: "video_url")
            param.updateValue(model.duration, forKey: "duration")
            param.updateValue(1, forKey: "type")
            
            append_model.type = .video
            append_model.duration = model.duration
            append_model.videoUrl = model.video_url
        }
        
        append_closure?(append_model)
        
        print("个人主页bug:",param)
        
        JVrequest(PH.addMyPhotoApi,parameters:param, success: { (json) in
            
            model.uploadStatus = .success
            
            model.state = 1
            
            model.id = json["data"]["id"].intValue
            
            self.modifyCellIndicator(key: model.content_key)
            
            
        }) { (code, err) in
            
            model.uploadStatus = .failure
            
            self.modifyCellIndicator(key: model.content_key)
        }
    }
    
    fileprivate func modifyCellIndicator(key:String){
        
        for item in collectionView.visibleCells{
            
            if let iCell = item as? ST_MyPhotoCollectionCell{
                
                if iCell.model.content_key == key{
                    
                    iCell.setting_uplaod_status()
                }
            }
        }
        
        
    }
    
}



//MARK: - Shared
class ST_MyPhotosSortManager: NSObject {
    
    static let  shared = ST_MyPhotosSortManager()
    
    
    func dis_appear_hanlde(data_array:[ST_MyPhotoCollectionCellModel]) {
        
        
        let uploadedArray = data_array.filtered({ (m) -> Bool in
            return m.uploadStatus == .success
        }) { (model) -> String in
            return model.content_key
        }
        
        let str = uploadedArray.joined(separator: ",")
        
        if uploadedArray.count >= 3{
            
            ST_PinterestHomeGuidanceManager.shared.unlock_look_new_girl()
            
        }
        
        let param = ["position":str]
        
        JVrequest(PH.sortMyPhotoApi, parameters : param ,success: { (json) in
            
            print("排序成功")
            
        }) { (code, err) in
            print("排序失败：",err)
        }
        
        
        
    }
    
}
